package com.tbit.uqbike.service.rpcservice;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @Author HZW
 * @ClassName AwardStrategyFactory
 * @Description
 * @date 2022/5/9 9:12
 * @Version 1.0
 */
@Component
public class AwardStrategyFactory implements ApplicationContextAware {
    private final static Map<String, AwardStrategy> MAP = new HashMap<>();

    public static synchronized AwardStrategyFactory getInstance() {
        if (CreateFactorySingleton.factory == null) {
            synchronized (AwardStrategyFactory.class) {
                if (CreateFactorySingleton.factory == null) {
                    CreateFactorySingleton.factory = new AwardStrategyFactory();
                }
            }
        }
        return CreateFactorySingleton.factory;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        Map<String, AwardStrategy> beanTypeMap = applicationContext.getBeansOfType(AwardStrategy.class);
        beanTypeMap.values().forEach(strategyObj -> MAP.put(strategyObj.getSource(), strategyObj));
    }

    /**
     * 对外统一暴露的工厂方法
     */

    public Boolean getAwardResult(String userCode, Integer money, String remark, String secret, String source) {
        AwardStrategy strategy = MAP.get(source);
        if (Objects.isNull(strategy)) {
            throw new RuntimeException("渠道异常!");
        }
        return strategy.finishRideOrder(userCode, money, remark, secret);
    }

    /**
     * 静态内部类创建单例工厂对象
     */
    private static class CreateFactorySingleton {
        private static volatile AwardStrategyFactory factory = new AwardStrategyFactory();
    }
}
